package test.mina;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

public class SimpleChatServerHandler extends IoHandlerAdapter {
	
	private Set<IoSession> onlines = Collections.synchronizedSet(new HashSet<>());

	@Override
	public void sessionCreated(IoSession session) throws Exception {
		onlines.add(session);
		broadcast(" has join the chat", session);
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {
		onlines.remove(session);
		broadcast(" has join the chat", session);
	}

	@Override
	public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
		System.out.println("[Server] IDLE " + session.getRemoteAddress()
        + session.getIdleCount(status));
	}

	@Override
	public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
		cause.printStackTrace();// (7)
        System.out.println("[Server] Client:" + session.getRemoteAddress()
                + "异常");
        // 遇到未捕获的异常，则关闭连接
        session.close(true);
	}

	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		String messageStr = message.toString();
		broadcast(messageStr, session);
	}

	@Override
	public void messageSent(IoSession session, Object message) throws Exception {
	}
	
	private void broadcast(String message, IoSession exceptSession) {
		for(IoSession session:onlines) {
			if(session.isConnected()) {
				if (session.equals(exceptSession)) {
	                session.write("[You]" + message);
	            } else {
	                session.write("[Client" + session.getRemoteAddress()
	                        + "] " + message);
	            }
			}
		}
	}

}
